package com.example.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.vo.Contact;
import com.google.gson.Gson;

public class JSONParser {
	// constructor
	public JSONParser() {

	}

	public JSONArray getJSONArrayFromString(InputStream is) {
		String json = "";

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;

			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

			is.close();
			json = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}

		JSONArray jArray = null;

		// try parse the string to a JSON array
		try {
			jArray = new JSONArray(json);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		// return JSON String
		return jArray;
	}

	public JSONObject getJSONObjectFromString(InputStream is) {
		String json = "";

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;

			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

			is.close();
			json = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}

		JSONObject jObj = null;

		// try parse the string to a JSON object
		try {
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		// return JSON String
		return jObj;
	}
	
	public String getJSONObjectFromObject(Contact contact) {
		Gson gson = new Gson();
		
		return gson.toJson(contact);
	}
}
